package com.sunday.shoufen.ui.index;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.CoordinatorLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.flyco.tablayout.SlidingTabLayout;
import com.flyco.tablayout.listener.OnTabSelectListener;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.sunday.common.model.ResultDO;
import com.sunday.common.utils.ToastUtils;
import com.sunday.common.widgets.banner.ConvenientBanner;
import com.sunday.common.widgets.banner.holder.ViewHolderCreator;
import com.sunday.shoufen.R;
import com.sunday.shoufen.adapter.AdHolder;
import com.sunday.shoufen.adapter.BannerHolder;
import com.sunday.shoufen.base.BaseLazyFragment;
import com.sunday.shoufen.entity.Ad;
import com.sunday.shoufen.entity.IndexClassify;
import com.sunday.shoufen.http.ApiClient;
import com.sunday.shoufen.ui.SearchShopListActivity;
import com.sunday.shoufen.ui.ShopListFragment;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

import static com.sunday.shoufen.R.id.btn_search;
import static com.sunday.shoufen.base.Constants.NEAR_BANNER;
import static com.sunday.shoufen.base.Constants.TEST_URL;


/**
 * Created by 刘涛 on 2017/10/17.
 */

public class NearByFragment extends BaseLazyFragment {

    @Bind(btn_search)
    TextView btnSearch;
    @Bind(R.id.slide_tab)
    SlidingTabLayout tabLayout;
    @Bind(R.id.appbar_layout)
    AppBarLayout appbarLayout;
    @Bind(R.id.view_pager)
    ViewPager viewPager;
    @Bind(R.id.coordinator_layout)
    CoordinatorLayout coordinatorLayout;
    @Bind(R.id.refresh_layout)
    SmartRefreshLayout refreshLayout;
    @Bind(R.id.banner)
    ConvenientBanner banner;

    private List<String> titles = new ArrayList<>();
    private List<IndexClassify> dataSet = new ArrayList<>();
    private List<Ad> adList = new ArrayList<>();

    public static NearByFragment newInstance() {
        NearByFragment fragment = new NearByFragment();
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        isPrepared = true;
        lazyLoad();
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.fragment_nearby, container, false);
        ButterKnife.bind(this, rootView);
        return rootView;
    }

    @Override
    protected void lazyLoad() {
        super.lazyLoad();
        if (!isPrepared || !isVisible) {
            return;
        }
        initView();
        isPrepared = false;
//        memberId= BaseApplication.getInstance().getMember().getId();
//        ptrFrame.autoRefresh();
        getAds();
    }


    private void initView() {
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {

                refreshData();
            }
        });
    }

    private void refreshData() {
        Call<ResultDO<List<Ad>>> call = ApiClient.getApiAdapter().getAdsByCode(NEAR_BANNER);
        call.enqueue(new Callback<ResultDO<List<Ad>>>() {
            @Override
            public void onResponse(Call<ResultDO<List<Ad>>> call, Response<ResultDO<List<Ad>>> response) {
                if (isFinish || response.body() == null) {
                    return;
                }
                refreshLayout.finishRefresh();
                if (response.body().getCode() == 0) {
                    adList.clear();
                    adList.addAll(response.body().getResult());
                    updateBanner();
                    ((ShopListFragment) fragments[viewPager.getCurrentItem()]).refresh();
                }
            }

            @Override
            public void onFailure(Call<ResultDO<List<Ad>>> call, Throwable t) {
                refreshLayout.finishRefresh();
            }
        });
    }

    private void getAds() {
        Call<ResultDO<List<Ad>>> call = ApiClient.getApiAdapter().getAdsByCode(NEAR_BANNER);
        call.enqueue(new Callback<ResultDO<List<Ad>>>() {
            @Override
            public void onResponse(Call<ResultDO<List<Ad>>> call, Response<ResultDO<List<Ad>>> response) {
                if (isFinish || response.body() == null) {
                    return;
                }
                if (response.body().getCode() == 0) {
                    adList.clear();
                    adList.addAll(response.body().getResult());
                    updateBanner();
                    getData();
                }
            }

            @Override
            public void onFailure(Call<ResultDO<List<Ad>>> call, Throwable t) {

            }
        });
    }

    private void updateBanner() {
        banner.startTurning(3000);
        final AdHolder indexAdHolder = new AdHolder();
        banner.setPages(new ViewHolderCreator<AdHolder>() {
            @Override
            public AdHolder createHolder() {
                return indexAdHolder;
            }
        }, adList)
                .setPageIndicator(new int[]{R.drawable.ic_page_indicator, R.drawable.ic_page_indicator_focused});
        banner.notifyDataSetChanged();
    }

    private void getData() {
        Call<ResultDO<List<IndexClassify>>> call = ApiClient.getApiAdapter().getShopCats();
        call.enqueue(new Callback<ResultDO<List<IndexClassify>>>() {
            @Override
            public void onResponse(Call<ResultDO<List<IndexClassify>>> call, Response<ResultDO<List<IndexClassify>>> response) {
                if (isFinish || response.body() == null) {
                    return;
                }
                if (response.body().getCode() == 0) {
                    titles.clear();
                    dataSet.clear();
                    dataSet.addAll(response.body().getResult());
                    if (!dataSet.isEmpty()) {
                        for (IndexClassify item : dataSet) {
                            titles.add(item.getName());
                        }
                        updateView();
                    }
                } else {
                    ToastUtils.showToast(mContext, response.body().getMessage());
                }
            }

            @Override
            public void onFailure(Call<ResultDO<List<IndexClassify>>> call, Throwable t) {
                ToastUtils.showToast(mContext, R.string.network_error);
            }
        });

    }


    @OnClick({btn_search})
    void onClick(){
        intent=new Intent(mContext, SearchShopListActivity.class);
        startActivity(intent);
    }

    private void updateView() {

        initFragment();
    }

    private Fragment[] fragments;

    private void initFragment() {
        viewPager.setAdapter(new PagerAdapter(getChildFragmentManager()));
        tabLayout.setViewPager(viewPager);
        viewPager.setCurrentItem(0, false);
        viewPager.setOffscreenPageLimit(titles.size());
    }

    public class PagerAdapter extends FragmentPagerAdapter {


        public PagerAdapter(FragmentManager fm) {
            super(fm);
            fragments = new Fragment[titles.size()];
        }

        @Override
        public Fragment getItem(int position) {
            if (fragments[position] == null) {
                fragments[position] = ShopListFragment.newInstance(dataSet.get(position).getId(),2);
            }
            return fragments[position];
        }

        @Override
        public int getCount() {
            return titles.size();
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return titles.get(position);
        }
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }
}
